<?php


namespace PKApp\Log\Classes;


use PKFrame\DataHandler\Arrays;
use PKFrame\Service;

class LogService extends Service
{

    public function interface_getEntityById($id, $viewField = '*')
    {
        // TODO: Implement interface_getEntityById() method.
    }

    protected function db(): LogDateBase
    {
        static $cls;
        !empty($cls) ?: $cls = new LogDateBase();
        return $cls;
    }

    public function GetList($viewParams = [], $viewField = '*', $index = 0, $line = 0)
    {
        return $this->db()->Where($viewParams)
            ->OrderBy('id')->Limit($line, $index)
            ->Select($viewField)->ToList();
    }

    public function GetCount($viewParams = []): int
    {
        return $this->db()->Where($viewParams)->Count();
    }

    public function GetEntity($viewParams = [], $viewField = '*')
    {
    }

    public function GetListOfArea(string $user_name)
    {
        $sql = <<<SQL
SELECT `userIPAreaId` FROM `pk_log` WHERE `userName` = '{$user_name}'  GROUP BY `userIPAreaId`
SQL;
        return $this->db()->SetSql([$sql])->ToList();
    }

    public function GetAndIsExistsLogState(string $state_en): string
    {
        static $list_log_state;
        !empty($list_log_state) ?: $list_log_state = dict('log_state', 'Log');
        return Arrays::GetKey($state_en, $list_log_state, 'state_en_noExists', 'Log');
    }

    public function GetAndIsExistsLogType(string $type_str): string
    {
        Arrays::GetKey($type_str, dict('log_type'), 'type_noExists', 'Log');
        return $type_str;
    }

    public function CreateLog(string $log_type, string $user_name, string $state_en,
                              string $log_content = null)
    {
        $ip = request()->GuestIP();
        try {
            $area = getLocationByIp($ip,'city');
            $this->Add([
                'logType' => $log_type,
                'userName' => $user_name,
                'userIP' => $ip,
                'userIPAreaId' => $area['cityId'],
                'userIPArea' => $area['city'],
                'userDevice' => request()->header('user-agent'),
                'logContent' => $log_content,
                'logStateEn' => $state_en,
                'logStateCn' => $this->GetAndIsExistsLogState($state_en),
                'createTime' => TIMESTAMP,
            ]);
        } catch (\Exception $e) {
            handlerException($e);
        }
    }
}